<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Timer" %>
<%@ page import="java.util.TimerTask" %>
<%@ page import="javax.script.*" %>

<%@page import="DBFunction.fSetAllOffline"%><html xmlns="http://www.w3.org/1999/xhtml">
<%
if(session.getAttribute("adminFirstName")==null)response.sendRedirect("index.jsp");; 

%>
    <head>
    	<title>Buddy Tracking Management Server</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" media="all" type="text/css" href="Css/Main.css"/>
		<link rel="stylesheet" href="jquery/themes/buddytracking/jquery.ui.all.css"> 
		<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>    
		<script src="jquery/jquery-1.5.1.js"></script> 
		<script src="js/jquery.validate.min.js"></script> 
		<script src="jquery/ui/jquery.ui.core.js"></script> 
		<script src="jquery/ui/jquery.ui.position.js"></script>
		<script src="jquery/ui/jquery.ui.widget.js"></script> 
		<script src="jquery/ui/jquery.ui.mouse.js"></script>
		<script src="jquery/ui/jquery.ui.draggable.js"></script>
		<script src="jquery/ui/jqwuery.ui.resizable.js"></script>
		<script src="jquery/ui/jquery.ui.button.js"></script>
		<script src="jquery/ui/jquery.ui.accordion.js"></script>
		<script src="jquery/ui/jquery.ui.dialog.js"></script>
		<script> 
		$(document).ready(function() {
			var contextPath = "${contextPath}";
			
			//var baseIcon = new google.maps.Icon(G_DEFAULT_ICON);
			
	        //var shadow = "http://www.google.com/mapfiles/shadow50.png";
	        var iconSize = new google.maps.Size(32, 32);
	        
	       	var shadowSize = new google.maps.Size(60, 32);
	        var iconAnchor = new google.maps.Point(16, 32);
	        var infoWindowAnchor = new google.maps.Point(16,0);
	       
	        var offImage = new google.maps.MarkerImage({
	        	url: contextPath+"/Css/Img/location_off.png",
	        	size: iconSize,
	    	    origin: iconAnchor,
	    	    anchor: infoWindowAnchor
	        });
	        
	        
	        initialize=function () {
	        	
		        //map.setCenter(new google.maps.LatLng(10.763159,106.655273), 8);
	        }
	        function createOfflineMarker(point,title,map) {
	            var image = contextPath+"/Css/Img/location_off.png";
	            var shadow = new google.maps.MarkerImage(contextPath+"/Css/Img/shadow.png",
	            	      new google.maps.Size(32, 32),
	            	      new google.maps.Point(0,0),
	            	      new google.maps.Point(8, 32));
	            var marker = new google.maps.Marker({
	            	position: point,
	                map: map,
	                icon: image,
	                shadow: shadow,
	                title: title
		        });
	            var infowindow = new google.maps.InfoWindow({
	                content: "<b>"+title+"</b>"
	            });
	            google.maps.event.addListener(marker, 'click', function() {
	            	  infowindow.open(map,marker);
	           	});
	            return marker;
	          }
	        function createOnlineMarker(point,title,map,name) {    
	            var marker = new google.maps.Marker({
	            	position: point,
	                map: map,
	                title: name
		        });
	            var infowindow = new google.maps.InfoWindow({
	                content: "<b style='color:red'>"+title+"</b>"
	            });
	            google.maps.event.addListener(marker, 'click', function() {
	            	  infowindow.open(map,marker);
	           	});
	            return marker;
	          }
			var inactiveLoaded = false;
			var selectedAll = false;
			var randomnumber=Math.floor(Math.random()*100000000);
			$("#inactiveHeader").click(function() {
				$(".memberSelect").removeAttr("checked");
				$(".memberSelectAll").removeAttr("checked");
				selectedAll = false;
				if(!inactiveLoaded){
					$.ajax({
					type: "GET",
					url: contextPath+"/ServerLoadInfo",
					data: "loadAction=loadInactive&rand="+randomnumber,
					success: function(response){
					$("#inactiveMemberDisplay").append(response);
					inactiveLoaded=true;
					$("#loadingImageRow1").empty();
					$(".memberInfo").click(function(){
						randomnumber=Math.floor(Math.random()*100000000);
						var userId = $(this).attr("id");
						var loadingImgPart = "<table id='memberInfoDisplay'><tr id='loadingImageRow2' align='center'><td  width='250px'><img id='loadingImage' src='Css/Img/ajax-loader.gif'></img></td></tr></table>"
						$.ajax({
							type: "GET",
							url: contextPath+"/ServerLoadInfo",
							data: "loadAction=loadMember&rand="+randomnumber+"&userId="+userId,
							success: function(response){
							 var data = $.parseJSON(response);
							$("#oldUserId").attr("value",data.id);
							$("#ePhoneNumber").attr("value",data.phoneNumber);
							$("#eFirstName").attr("value",data.firstName);
							$("#eLastName").attr("value",data.lastName);
							$("#eEmail").attr("value",data.email);
							$("#eAddress").attr("value",data.address);
							}
							});
						$("#memberInfoDialog").dialog("open");
						$("#loadingImageRow2").empty();
					});
					}
					});
				}
			});
			$(".memberInfo").click(function(){
				randomnumber=Math.floor(Math.random()*100000000);
				var userId = $(this).attr("id");
				var loadingImgPart = "<table id='memberInfoDisplay'><tr id='loadingImageRow2' align='center'><td  width='250px'><img id='loadingImage' src='Css/Img/ajax-loader.gif'></img></td></tr></table>"
				$.ajax({
					type: "GET",
					url: contextPath+"/ServerLoadInfo",
					data: "loadAction=loadMember&rand="+randomnumber+"&userId="+userId,
					success: function(response){
					 var data = $.parseJSON(response);
					$("#oldUserId").attr("value",data.id);
					$("#ePhoneNumber").attr("value",data.phoneNumber);
					$("#eFirstName").attr("value",data.firstName);
					$("#eLastName").attr("value",data.lastName);
					$("#eEmail").attr("value",data.email);
					$("#eAddress").attr("value",data.address);
					}
					});
				$("#memberInfoDialog").dialog("open");
				$("#loadingImageRow2").empty();
			});

			$(".mapLocation").click(function() {
				var groupName = $(this).attr("id");
				randomnumber=Math.floor(Math.random()*100000000);
				$.ajax({
					type: "GET",
					url: contextPath+"/ServerLoadInfo",
					data: "loadAction=loadPosition&rand="+randomnumber+"&groupName="+groupName,
					success: function(response){
					var prefix ='{"User":' ;
					var subfix ='}';
					var data = prefix+response+subfix;
					var positionList = eval("(" + data + ")");
					var x=0;
					var firstUserPosition = new google.maps.LatLng(positionList.User[0].latitude, positionList.User[0].longitude);
					var myOptions = {
		        		    zoom: 8,
		        		    center: firstUserPosition,
		        		    mapTypeId: google.maps.MapTypeId.ROADMAP
		        		  }
		        	var map = new google.maps.Map(document.getElementById("mapLocationDialog"),myOptions);
					$.each(positionList.User, function(i,User) {
						var latlng = new google.maps.LatLng(User.latitude, User.longitude);
						if(User.isOnline == "Offline"){
						title = User.firstName +" "+ User.lastName + ", Last Online : "+User.lastUpdate;
						marker = createOfflineMarker(latlng,title,map);
						
						marker.setMap(map);
						}
						else {			
							title = User.firstName +" "+ User.lastName+" <p style='color:black'>Number: " +User.phoneNumber+"</p>";
							name =User.firstName +" "+User.lastName;
							marker = createOnlineMarker(latlng,title,map,name);
							marker.setMap(map);
							
						}
						});
					}
				});
				$("#mapLocationDialog").dialog("open");
				 
			});
			
			$.validator.addMethod("NumbersOnly", function(value, element) {
		        return this.optional(element) || /^[0-9\-\+]+$/i.test(value);
		    }, "Phone must contain only numbers, + and -.");
					
			$("#addMemberForm").validate();
			$("#editMemberForm").validate();
			$("#addGroupForm").validate();
			$("#changeGroupNameForm").validate();
		});
		
		$(function() {
			var selectedAll = false;
			$("button, input:submit, .submit, #logout,#refresh,#config,.addMemberButton,.deleteMemberButton,.moveMemberButton,.editGroupButton,.deleteGroupButton,.mapLocation", "#managementbody" ).button();
			$('#accordion').accordion({
			autoHeight: false,
			navigation: true,
			collapsible: true,
			header: "h3"
			});
			$("#addMemberDialog").dialog({
				autoOpen:false,
				modal:true,
				draggable:true,
				resizable: false,
				closeOnEscape:true,
				autoHeight : true,
				title :'Add New Member',
				buttons: { "Ok": function() { $("#addMemberForm").submit(); } ,
				 "Cancel": function() { $(this).dialog("close"); $("#addMemberForm")[0].reset();var form=$("#addMemberForm").validate();form.resetForm();} }
			});
			$("#memberInfoDialog").dialog({
				autoOpen:false,
				modal:true,
				draggable:true,
				resizable: false,
				closeOnEscape:true,
				autoHeight : true,
				title :'Member Information',
				buttons: { "Ok": function() {  $("#editMemberForm").submit(); } ,
				 "Cancel": function() { $(this).dialog("close"); $("#editMemberForm")[0].reset();var form=$("#editMemberForm").validate();form.resetForm();} }
			});
			$("#addGroupDialog").dialog({
				autoOpen:false,
				modal:true,
				draggable:true,
				resizable: false,
				closeOnEscape:true,
				autoHeight : true,
				title :'Add New Group',
				buttons: { "Ok": function() { $("#addGroupForm").submit(); } ,
						 "Cancel": function() { $(this).dialog("close");var form=$("#addGroupForm").validate();form.resetForm();}
						 }
			});
			$("#deleteGroupDialog").dialog({
				autoOpen:false,
				modal:true,
				draggable:true,
				resizable: false,
				closeOnEscape:true,
				autoHeight : true,
				width : 300,
				title :'Delete Group',
				buttons: { "Ok": function() { $("#deleteGroupForm").submit(); } ,
				 "Cancel": function() { $(this).dialog("close"); } }
			});
			$("#changeGroupNameDialog").dialog({
				autoOpen:false,
				modal:true,
				draggable:true,
				resizable: false,
				closeOnEscape:true,
				autoHeight : true,
				title :'Change Group Name',
				buttons: { "Ok": function() { $("#changeGroupNameForm").submit(); } ,
				 "Cancel": function() { $(this).dialog("close");var form=$("#changeGroupNameForm").validate();form.resetForm();} }
			});
			$(".addMemberButton").click(function(){
				$(".userAction").val("add");
				$("#addUserGroupName").val($(this).attr("id"));
				$("#addMemberDialog").dialog("open");
			});
			$(".moveMemberButton").click(function(){
				$(".userAction").val("move");
				$("#oldGroupName").val($(this).attr("id"));
				$("#userManageForm").submit();
			});
			$(".deleteMemberButton").click(function(){
				$(".userAction").val("delete");
				$("#userManageForm").submit();
			});
			$(".deleteGroupButton").click(function(){
				$("#deleteGroupName").val($(this).attr("id"));
				$("#deleteGroupText").text($(this).attr("id"));
				$("#deleteGroupAction").val("delete");
				$("#deleteGroupDialog").dialog("open");
			});
			$(".editGroupButton").click(function(){
				$(".oldGroupName").val($(this).attr("id"));
				$("#inputGroupName").val($(this).attr("id"));
				$("#changeGroupNameDialog").dialog("open");
				
			});
			$(".accheader").click(function() {
				$(".memberSelect").removeAttr("checked");
				$(".memberSelectAll").removeAttr("checked");
				selectedAll = false;
			});
			$("#addNewGroup").click(function(){
				$("#addGroupAction").val("add");
				$("#addGroupDialog").dialog("open");
			});
			$(".addMemberButton").click(function(){
				$("#addMemberDialog").dialog("open");
			});
			$("#logout").click(function() {$("#logoutform").submit(); });
			$("#refresh").click(function() {$("#callServerDisplay").submit(); });
			$("#config").click(function() {$("#callAdminDisplay").submit(); });
			$(".memberSelectAll").click(function() {
				if(selectedAll) {
					$(this).parent().parent().parent().parent().find(".memberSelect").removeAttr("checked");
					selectedAll=false;
				}
				else {$(this).parent().parent().parent().parent().find(".memberSelect").attr("checked","true");selectedAll=true;}
			});
			$("#inactiveHeader").click(function() {
				$(".memberSelect").removeAttr("checked");
				$(".memberSelectAll").removeAttr("checked");
				selectedAll = false;
				$("#inactiveMemberDisplay").load("ServerLoadInfo.java");
			});
			
		    
			$("#mapLocationDialog").dialog({
				autoOpen:false,
				modal:true,
				draggable:true,
				resizable: true,
				closeOnEscape:true,
				height : 500,
				width: 500,
				title :'Map Location',
				open: function(event, ui) {initialize();}
			});
		});
		</script>
    </head>
    <body >
    	<div id="managementbody">
    	<form id="logoutform" method="GET" action="ServerAdminLogout"></form>
    		<div id="banner"><div id="welcomelabel">Welcome ${adminLastName}&nbsp;${adminFirstName}&nbsp;&nbsp;&nbsp;</div><div id="navigation"><a id="refresh" name="refresh" >Reload</a><a id="config" name="config">Configuration</a><a id="logout" name="logout" >Sign Out</a></div></div>
			<form method="get" name="callAdminDisplay" id="callAdminDisplay" action="ServerAdminDisplay"></form>
			<div id="managementpage">
				<div id="accordion">
				<form method="get" name="userManageForm" id="userManageForm" action="ServerUserManager">
				<input type="hidden" name="userAction" class="userAction" value=""/>
				<input type="hidden" name="oldGroupName" id="oldGroupName" class="oldGroupName" value=""/>
				<c:forEach items="${Group}" var="currentGroup">
					<h3><a class="accheader" href="#">Group : ${currentGroup.groupName }</a></h3> 
					<div id="${currentGroup.groupName}">
						<table >
							<tr align="center">
								<td><input class ="memberSelectAll" type="checkbox" value="memberSelectAll"></td>
								<td><a class="addMemberButton" id="${currentGroup.groupName }">Add Member</a></td>
								<td><a class="moveMemberButton" id="${currentGroup.groupName }">Move To</a></td>
								<td><select name="moveToGroupFrom${currentGroup.groupName }" class="moveToGroup" id="${currentGroup.groupName }"><c:forEach items="${Group}" var="groupOption"><option>${groupOption.groupName }</option></c:forEach><option>Inactive</option></select></td>
								<td><a class="editGroupButton" id="${currentGroup.groupName }">Change Group Name</a></td>
								<td><a class="deleteGroupButton" id="${currentGroup.groupName }">Delete Group</a></td>
								<td><a class="mapLocation" id="${currentGroup.groupName }"onclick="initialize();">Map Location</a></td>
							</tr>
							<c:forEach items="${currentGroup.userList}" var="currentUser">
							<tr align="center">
								<td><input name="memberSelect" class ="memberSelect" type="checkbox" value="${currentUser.id }"></td>
								<td><a href="#" class="memberInfo" id="${currentUser.id }">${currentUser.firstName }&nbsp;${currentUser.lastName }</a></td>
								<td>${currentUser.phoneNumber }</td>
								<td class="${currentUser.isOnline }">${currentUser.isOnline }</td>
							</tr>
							</c:forEach>
						</table>
					</div>
					</c:forEach>
					<h3><a class="accheader" id="inactiveHeader" href="#">Group : Inactive</a></h3> 
					<div id="inactiveGroup">
						<table id="inactiveMemberDisplay">
							<tr align="center">
								<td><input class ="memberSelectAll" type="checkbox" value="memberSelectAll"></td>
								<td><a class="addMemberButton" id="Inactive">Add Member</a></td>
								<td><a class="deleteMemberButton" id="Inactive">Delete Member</a></td>
								<td><a class="moveMemberButton" id="Inactive">Move To</a></td>
								<td><select name="moveToGroupFromInactive" class="moveToGroup" id="${currentGroup.groupName }"><c:forEach items="${Group}" var="groupOption"><option>${groupOption.groupName }</option></c:forEach></select></td>
							</tr>
							<tr id="loadingImageRow1" align="center"><th colspan=2></th>
								<td><img id="loadingImage" src="Css/Img/ajax-loader.gif"></img></td>
							</tr>						
						</table>
					</div>
				</form>
					<h3><a class="accheader" id="addNewGroup" href="#">Add New Group</a></h3> 
				</div>
			</div>
    	</div>
		<div id="footer">
			Developed by <b>Pham Hong Phuc & Nguyen Hoang Quan</b>
		</div>
		<div id="footer">
			<b>Buddy Tracking</b> System
		</div>
		<div id="addMemberDialog" >
			<form method="GET" id="addMemberForm" action="ServerUserManager">
			<input type="hidden" name="userAction" class="userAction" value="add"/>
			<input type="hidden" name="addUserGroupName" id="addUserGroupName" value=""/>
			<table id="">
				<tr>
					<td>Phone Number</td>
				</tr>
				<tr>
					<td><input class="required NumbersOnly" minlength="8" maxlength="10" type="text" name="phoneNumber" id="PhoneNumber"/></td>
				</tr>
				<tr>
					<td>Passwords</td>
				</tr>
				<tr>
					<td><input class="required" minlength="5" maxlength="30" type="password" name="passwords" id="Passwords"/></td>
				</tr>
				<tr>
					<td>Retype Passwords</td>
				</tr>
				<tr>
					<td><input class="required" minlength="5" maxlength="30" equalTo="#Passwords" type="password" name="rePasswords"id="RetypePasswords"/></td>
				</tr>
				<tr>
					<td>First Name</td>
				</tr>
				<tr>
					<td><input class="required" minlength="2" maxlength="40"type="text" name="firstName" id="FirstName"/></td>
				</tr>
				<tr>
					<td>Last Name</td>
				</tr>
				<tr>
					<td><input class="required" minlength="2" maxlength="40" type="text" name="lastName" id="LastName"/></td>
				</tr>
				<tr>
					<td>Email</td>
				</tr>
				<tr>
					<td><input class="required email" maxlength="40" type="text" name="email" id="Email"/></td>
				</tr>
				<tr>
					<td>Address</td>
				</tr>
				<tr>
					<td><input class="required" maxlength="40" type="text" name="address" id="Address"/></td>
				</tr>						
			</table>
			</form>
		</div>
		
		<div id=memberInfoDialog>
		<form id="editMemberForm" method="GET" action="ServerUserManager">
		<input type="hidden" name="userAction" value="edit"/>
		<input type="hidden" name="oldUserId" id="oldUserId" value="edit"/>
			<table id="memberInfoDisplay">
				<tr id="loadingImageRow2" align="center">
					<td  width="250px"><img id="loadingImage" src="Css/Img/ajax-loader.gif"></img></td>
				</tr>
				<tr>
					<td>Phone Number</td>
				</tr>
				<tr>
					<td><input class="required NumbersOnly" minlength="8" maxlength="10" type="text" name="phoneNumber" id="ePhoneNumber"/></td>
				</tr>
				<tr>
					<td>New Passwords</td>
				</tr>
				<tr>
					<td><input class="addForm" minlength="5" maxlength="30" type="password" name="passwords" id="ePasswords"/></td>
				</tr>
				<tr>
					<td>Retype New Passwords</td>
				</tr>
				<tr>
					<td><input class="addForm" minlength="5" maxlength="30" equalTo="#ePasswords" type="password" name="eReTypePasswords"id="RetypePasswords"/></td>
				</tr>
				<tr>
					<td>First Name</td>
				</tr>
				<tr>
					<td><input class="required" minlength="2" maxlength="40" type="text" name="firstName" id="eFirstName"/></td>
				</tr>
				<tr>
					<td>Last Name</td>
				</tr>
				<tr>
					<td><input class="required" minlength="2" maxlength="40" type="text" name="lastName" id="eLastName"/></td>
				</tr>
				<tr>
					<td>Email</td>
				</tr>
				<tr>
					<td><input class="required email" maxlength="40" type="text" name="email" id="eEmail"/></td>
				</tr>
				<tr>
					<td>Address</td>
				</tr>
				<tr>
					<td><input class="required"  maxlength="40"type="text" name="address" id="eAddress"/></td>
				</tr>	
			</table>
			</form>		
		</div>
		
		<div style="display:none" ><input type="reset" id="addMemberFormReset"/></div>
		<div style="display:none" ><input type="reset" id="editMemberFormReset"/></div>
		<div id="addGroupDialog" >
			<form method="GET" id="addGroupForm" action="ServerGroupManager">
			<input type="hidden" name="groupAction" id="addGroupAction" value="add"/>
			<table>
				<tr>
					<td>Group Name</td>
				</tr>
				<tr>
					<td><input class="required" minlength="2" type="text" name="inputGroupName" maxlength="40"/></td>
				</tr>
			</table>
			</form>
		</div>
		
		<div id="deleteGroupDialog" >
			<form method="GET" id="deleteGroupForm" action="ServerGroupManager">
			<input type="hidden" name="groupAction" id="deleteGroupAction" value="delete"/>
			<input type="hidden" name="deleteGroupName" id="deleteGroupName" value=""/>
			</form>
			Are you sure you want to delete this group ?<p id="deleteGroupText"></p>
		</div>
		<div id="changeGroupNameDialog" >
			<form method="GET" id="changeGroupNameForm" action="ServerGroupManager">
			<input type="hidden" name="oldGroupName" id="oldGroupName" class="oldGroupName" value=""/>
			<input type="hidden" name="groupAction" id="changeGroupNameAction" value="changename"/>
			<table>
				<tr>
					<td>New Name</td>
				</tr>
				<tr>
					<td><input class="required" minlength="2" type="text" id="inputGroupName" name="inputGroupName" maxlength="40"/></td>
				</tr>
			</table>
			</form>
		</div>
		<div id="mapLocationDialog"></div>
		<form method="get" name="callServerDisplay"  id="callServerDisplay" action="ServerDisplay"></form>
    </body>
</html>
<script type="text/javascript"> 
<%

int delay = 1*60*1000;   // 1 minutes delay
int period = 10*60*1000;  // repeat every 10 minutes
Timer timer = new Timer();
//final ScriptEngineManager manager = new ScriptEngineManager();
//final ScriptEngine engine = manager.getEngineByName("JavaScript");
//final String js="print ('www.java2s.com')";

timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            fSetAllOffline.process();
            // refresh servlet go here
           	}
    }, delay, period);
%>
</script>